<template>
  <div class="admin-management">
    <!-- 上部分：筛选条件 -->
    <div class="filter-bar">
      <div class="filter-controls">
        <el-input
            v-model="filterAccount"
            placeholder="遥测数据参数类型名称"
            clearable
            style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>·
        <el-select
            v-model="filterStatus"
            placeholder="遥测数据参数类型状态"
            clearable
            style="width: 120px"
        >
          <el-option label="全部状态" value="" />
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
        <el-button type="primary" @click="searchTasks">
          查询
        </el-button>
        <el-button @click="resetFilter">
          重置
        </el-button>
      </div>
    </div>

    <!-- 下部分：遥测数据参数类型表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>遥测数据参数类型列表</h3>
        <div class="table-controls">
          <el-button size="small" type="success" @click="addNewTask">
            添加遥测数据参数类型
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
            :data="paginatedTaskData"
            style="width: 100%; height: 100%;"
            stripe
            :header-cell-style="{ background: '#f8f9fa', color: '#333', fontWeight: '500', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            border
            v-loading="loading"
        >
          <el-table-column prop="id" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="遥测数据参数类型名称" min-width="150" align="center" />
          <el-table-column prop="taskTypeName" label="任务类型" min-width="150" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getTaskStatusType(scope.row.status)" size="small">
                {{ getTaskStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="warning" @click="editTask(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="deleteTask(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ total }} 条记录，当前显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, total) }} 条</span>
        </div>
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
        />
      </div>
    </div>

    <!-- 添加/编辑遥测数据参数类型弹窗 -->
    <el-dialog
        v-model="showAddDialog"
        :title="isEdit ? '编辑遥测数据参数类型' : '添加遥测数据参数类型'"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="taskForm" label-width="180px" :rules="taskRules" ref="taskFormRef">
        <el-form-item label="遥测数据参数类型名称" prop="name">
          <el-input
              v-model="taskForm.name"
              placeholder="请输入遥测数据参数类型名称"
              maxlength="50"
              show-word-limit
              :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskTypeId">
          <el-tree-select
              v-model="taskForm.taskTypeId"
              :data="taskTypeOptions"
              :check-strictly="true"
          :render-after-expand="false"
          placeholder="请选择任务类型"
          style="width: 100%"
          :props="{label: 'label', children: 'children'}"
          :show-checkbox="false"
          @node-click="handleNodeClick"
          />
        </el-form-item>
        <el-form-item label="遥测数据参数类型状态" prop="status">
          <el-select v-model="taskForm.status" placeholder="请选择遥测数据参数类型状态" style="width: 100%">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button
            type="primary"
            @click="saveTask"
            :loading="saveLoading"
        >
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { telemetryDataAPI,taskTypeAPI } from '../api/index.js'

const router = useRouter()

// 响应式数据
const filterAccount = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showAddDialog = ref(false)
const isEdit = ref(false)
const taskFormRef = ref()
const loading = ref(false)
const saveLoading = ref(false)
const taskTypeOptions = ref([])

// 遥测数据参数类型列表数据
const taskList = ref([])

// 遥测数据参数类型表单数据
const taskForm = ref({
  id: '',
  name: '',
  taskTypeId: '', // 改为字符串类型
  status: '0'
})

// 表单验证规则
const taskRules = {
  name: [
    { required: true, message: '请输入遥测数据参数类型名称', trigger: 'blur' },
    { min: 4, max: 20, message: '名称长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  taskTypeId: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择遥测数据参数类型状态', trigger: 'change' }
  ]
}

const handleNodeClick = (node) => {
  // 单选模式下直接设置选中的value
  taskForm.value.taskTypeId = node.value;
};

// 加载遥测数据参数类型列表
const loadTaskList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      name: filterAccount.value || '',
      status: filterStatus.value || ''
    };

    const result = await telemetryDataAPI.getTelemetryDataList(params);

    if (result && result.code === 0) {
      taskList.value = result.rows || [];
      total.value = result.total || 0;
    } else {
      throw new Error(result?.msg || '获取遥测数据参数类型列表失败');
    }
  } catch (error) {
    console.error('加载遥测数据参数类型列表失败:', error);
    ElMessage.error(`加载遥测数据参数类型列表失败: ${error.message}`);
    taskList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载任务类型选项
const loadTaskTypeOptions = async () => {
  try {
    const result = await taskTypeAPI.getTaskTypeList();
    if (result && result.code === 0) {
      // 转换数据格式为el-tree-select需要的结构
      const transformData = (items) => {
        return items.map(item => ({
          value: item.id,  // 使用id作为value
          label: item.typeName,  // 使用typeName作为显示文本
        }));
      };

      taskTypeOptions.value = transformData(result.data || []);
    } else {
      throw new Error(result?.msg || '获取任务类型失败');
    }
  } catch (error) {
    console.error('加载任务类型失败:', error);
    ElMessage.error(`加载任务类型失败: ${error.message}`);
    taskTypeOptions.value = [];
  }
};

// 分页数据
const paginatedTaskData = computed(() => {
  return taskList.value;
});

const taskTypeNameMap = computed(() => {
  const map = {}
  const buildMap = (nodes) => {
    nodes.forEach(node => {
      map[node.value] = node.label
      if (node.children) buildMap(node.children)
    })
  }
  buildMap(taskTypeOptions.value)
  return map
})

// 状态显示函数
const getTaskStatusType = (status) => {
  const statusMap = {
    '0': 'success',   // 正常
    '1': 'danger'     // 停用
  };
  return statusMap[status] || 'info';
};

const getTaskStatusText = (status) => {
  const statusMap = {
    '0': '正常',
    '1': '停用'
  };
  return statusMap[status] || '未知';
};

// 业务操作函数
const searchTasks = async () => {
  currentPage.value = 1
  await loadTaskList()
}

const resetFilter = async () => {
  filterAccount.value = ''
  filterStatus.value = ''
  currentPage.value = 1
  await loadTaskList()
  ElMessage.info('已重置筛选条件')
}

const addNewTask = async () => {
  isEdit.value = false
  resetForm()
  showAddDialog.value = true
  // 加载任务类型选项
  await loadTaskTypeOptions()
}

const editTask = async (row) => {
  isEdit.value = true
  console.log('正在编辑遥测数据参数类型，ID:', row);
  taskForm.value = {
    id: row.id,
    name: row.name,
    taskTypeId: row.taskTypeId || '',
    status: row.status.toString() // 确保是字符串
  }

  showAddDialog.value = true
  // 加载任务类型选项
  await loadTaskTypeOptions()
  // 确保树形选择器正确显示已选项
  nextTick(() => {
    if (taskFormRef.value) {
      taskFormRef.value.clearValidate()
    }
  })
}

const saveTask = async () => {
  try {
    await taskFormRef.value.validate();
    saveLoading.value = true;

    const taskData = {
      name: taskForm.value.name,
      taskTypeId: taskForm.value.taskTypeId, // 直接使用字符串
      status: taskForm.value.status
    };

    let result;
    if (isEdit.value) {
      result = await telemetryDataAPI.updateTelemetryData(taskForm.value.id,taskData); // 补充更新调用
    } else {
      result = await telemetryDataAPI.addTelemetryData(taskData);
    }

    if (result?.code === 0) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
      showAddDialog.value = false;
      await loadTaskList();
    } else {
      throw new Error(result?.msg || '操作失败');
    }
  } catch (error) {
    console.error('保存失败:', error.response?.data || error);
    ElMessage.error(`操作失败: ${error.response?.data?.msg || error.message}`);
  } finally {
    saveLoading.value = false;
  }
};

const cancelEdit = () => {
  showAddDialog.value = false
  nextTick(() => {
    resetForm()
  })
}

const resetForm = () => {

  taskForm.value = {
    id: '',
    name: '',
    taskTypeId: '', // 改为空字符串
    status: '0'
  }
  nextTick(() => {
    if (taskFormRef.value && typeof taskFormRef.value.resetFields === 'function') {
      taskFormRef.value.resetFields()
    }
  })
}

const deleteTask = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除遥测数据参数类型"${row.name}"吗？\n\n此操作不可恢复！`,
        '确认删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const result = await telemetryDataAPI.deleteTelemetryData(row.id);

    if (result && result.code === 0) {
      ElMessage.success('删除成功');
      await loadTaskList();
    } else {
      throw new Error(result?.msg || '删除遥测数据参数类型失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除遥测数据参数类型失败:', error);
      ElMessage.error(`删除遥测数据参数类型失败: ${error.message}`);
    }
  }
}

// 分页处理
const handleSizeChange = async (val) => {
  pageSize.value = val
  currentPage.value = 1
  await loadTaskList()
}

const handleCurrentChange = async (val) => {
  currentPage.value = val
  await loadTaskList()
}

onMounted(async () => {
  await loadTaskList();
});
computed
</script>

<style scoped>
/* 保持原有样式不变 */
.admin-management {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-bar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.filter-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-controls {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  padding: 0 20px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}
</style>
